# -*- coding: utf-8 -*-
# File : feed_trace.py
# Author: taoyahui
# Date : 2021/7/20
import json
from HelloWorld import utils
from HelloWorld.models import Contract
# from HelloWorld.service.contract_abi import feed_trace_abi
import results
import time
import requests
from django.http import HttpResponse


def set_user_role(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    opt_user_address = res_json['user']
    address = res_json['address']
    role = res_json['role']
    contract_list = Contract.objects.filter(name="FeedTraceTest")
    if len(contract_list) == 0:
        return HttpResponse(json.dumps(results.system_error_result))
    contract = contract_list[0]
    feed_trace_abi = json.loads(contract.abi)

    data = {
        "groupId": "1",
        "user": opt_user_address,
        "contractName": "FeedTraceTest",
        # "contractPath": "FeedTrace",
        "version": "",
        "funcName": "setUserRole",
        "funcParam": [address, role],
        "contractAddress": contract.address,
        "contractAbi": feed_trace_abi,
        "useAes": False,
        "useCns": False,
        "cnsName": ""
    }
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url="http://localhost:5002/WeBASE-Front/trans/handle",
                        headers=headers,
                        data=json.dumps(data).replace("False", "false").replace("True", "true"))
    if res.status_code == 200:
        return HttpResponse(json.dumps({
            'code': 200,
            'data': res.text
        }))
    else:
        return HttpResponse(json.dumps({
            'code': res.status_code,
            'data': res.text
        }))


def get_user_role(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    opt_user_address = res_json['user']
    address = res_json['address']
    contract_list = Contract.objects.filter(name="FeedTraceTest")
    if len(contract_list) == 0:
        return HttpResponse(json.dumps(results.system_error_result))
    contract = contract_list[0]
    feed_trace_abi = json.loads(contract.abi)
    data = {
        "groupId": "1",
        "user": opt_user_address,
        "contractName": "FeedTraceTest",
        # "contractPath": "FeedTrace",
        "version": "",
        "funcName": "getUserRole",
        "funcParam": [address],
        "contractAddress": contract.address,
        "contractAbi": feed_trace_abi,
        "useAes": False,
        "useCns": False,
        "cnsName": ""
    }
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url="http://localhost:5002/WeBASE-Front/trans/handle",
                        headers=headers,
                        data=json.dumps(data).replace("False", "false").replace("True", "true"))
    print(res)
    if res.status_code == 200:
        role = json.loads(res.text)[0]
        return HttpResponse(json.dumps({
            'code': 200,
            'data': role
        }))
    else:
        return HttpResponse(json.dumps({
            'code': res.status_code,
            'data': res.text
        }))


def create_feed(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    feed_name = res_json['feed_name']
    feed_type = res_json['feed_type']
    feed_price = res_json['feed_price']
    opt_user_address = res_json['user']
    contract_list = Contract.objects.filter(name="FeedTraceTest")
    if len(contract_list) == 0:
        return HttpResponse(json.dumps(results.system_error_result))
    contract = contract_list[0]
    feed_trace_abi = json.loads(contract.abi)
    data = {
        "groupId": "1",
        "user": opt_user_address,
        "contractName": "FeedTraceTest",
        # "contractPath": "FeedTrace",
        "version": "",
        "funcName": "createFeed",
        "funcParam": [feed_name, feed_type, feed_price, utils.get_time_int()],
        "contractAddress": contract.address,
        "contractAbi": feed_trace_abi,
        "useAes": False,
        "useCns": False,
        "cnsName": ""
    }
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url="http://localhost:5002/WeBASE-Front/trans/handle",
                        headers=headers,
                        data=json.dumps(data).replace("False", "false").replace("True", "true"))

    return HttpResponse(json.dumps({
        'code': res.status_code,
        'data': res.text
    }))


def get_feed(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    opt_user_address = res_json['user']
    feed_no = res_json['feed_no']
    func_param = [feed_no]
    res = common_feed_trace_request(opt_user_address, "getFeed", func_param)
    if res.status_code == 200:
        result_list = json.loads(res.text)
        str = f"名称: {result_list[0]},类型: {result_list[1]}, 价格:{result_list[2]}, 时间戳:{result_list[3]} "
        return HttpResponse(json.dumps({
            'code': res.status_code,
            'data': str
        }))
    else:
        return HttpResponse(json.dumps({
            'code': res.status_code,
            'data': res.text
        }))


def create_order(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    opt_user_address = res_json['user']
    price = res_json['order_price']
    food_type = res_json['food_type']
    feed_no = res_json['feed_no']
    func_param = [utils.get_time_int(), price, food_type, feed_no]
    res = common_feed_trace_request(opt_user_address, "createOrder", func_param)
    return HttpResponse(json.dumps({
        'code': res.status_code,
        'data': res.text
    }))


def get_order(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    opt_user_address = res_json['user']
    order_no = res_json['order_no']
    func_param = [order_no]
    res = common_feed_trace_request(opt_user_address, "getOrder", func_param)
    if res.status_code == 200:
        return HttpResponse(json.dumps({
            'code': res.status_code,
            'data': res.text
        }))
    else:
        return HttpResponse(json.dumps({
            'code': res.status_code,
            'data': res.text
        }))


def create_specific_order(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    opt_user_address = res_json['user']
    order_type = int(res_json['order_type'])
    parent_order_no = res_json['parent_order_no']
    order_price = res_json['order_price']
    order_detail = res_json['order_detail']
    order_feed_no = res_json['order_feed_no']
    func_param = [parent_order_no, int(time.time()), order_price, order_detail, order_feed_no]
    if order_type == 1:
        res = common_feed_trace_request(opt_user_address, "createProduceOrder", func_param)
    elif order_type == 2:
        res = common_feed_trace_request(opt_user_address, "createProcessOrder", func_param)
    elif order_type == 3:
        res = common_feed_trace_request(opt_user_address, "createTransportOrder", func_param)
    elif order_type == 4:
        res = common_feed_trace_request(opt_user_address, "createStorateOrder", func_param)
    elif order_type == 5:
        res = common_feed_trace_request(opt_user_address, "createSellOrder", func_param)
    else:
        return HttpResponse(json.dumps(results.system_error_result))
    return HttpResponse(json.dumps({
        'code': res.status_code,
        'data': res.text
    }))


def get_specific_order(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    opt_user_address = res_json['user']
    order_type = int(res_json['order_type'])
    parent_order_no = res_json['parent_order_no']
    func_param = [parent_order_no]
    if order_type == 1:
        res = common_feed_trace_request(opt_user_address, "getProduceOrder", func_param)
    elif order_type == 2:
        res = common_feed_trace_request(opt_user_address, "getProcessOrder", func_param)
    elif order_type == 3:
        res = common_feed_trace_request(opt_user_address, "getTransportOrder", func_param)
    elif order_type == 4:
        res = common_feed_trace_request(opt_user_address, "getStorateOrder", func_param)
    elif order_type == 5:
        res = common_feed_trace_request(opt_user_address, "getSellOrder", func_param)
    else:
        return HttpResponse(json.dumps(results.system_error_result))
    if res.status_code == 200:
        json_array = json.loads(res.text)
        json_dict = {
            "订单编号": json_array[0],
            "订单类型": json_array[1],
            "创建时间": json_array[2],
            "价格": json_array[3],
            "详情":json_array[4],
            "食品编号":json_array[5],
            "订单作者地址":json_array[6]
        }
        return HttpResponse(json.dumps({
        'code': res.status_code,
        'data': json_dict
    }))

    else:
        return HttpResponse(json.dumps({
        'code': res.status_code,
        'data': res.text
    }))




def common_feed_trace_request(opt_user_address, func_name, func_param):
    contract_list = Contract.objects.filter(name="FeedTraceTest")
    if len(contract_list) == 0:
        return HttpResponse(json.dumps(results.system_error_result))
    contract = contract_list[0]
    feed_trace_abi = json.loads(contract.abi)
    data = {
        "groupId": "1",
        "user": opt_user_address,
        "contractName": "FeedTraceTest",
        # "contractPath": "FeedTrace",
        "version": "",
        "funcName": func_name,
        "funcParam": func_param,
        "contractAddress": contract.address,
        "contractAbi": feed_trace_abi,
        "useAes": False,
        "useCns": False,
        "cnsName": ""
    }
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url="http://localhost:5002/WeBASE-Front/trans/handle",
                        headers=headers,
                        data=json.dumps(data).replace("False", "false").replace("True", "true"))
    return res